<?php

namespace App\Services\RegisterNewUser;

use Closure;
use App\Supports\Sms\Sms;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class RegisterNewUserRequest extends FormRequest
{
	public function rules(): array
	{
		return [
			'invite_code' => 'nullable|string|min:10|max:10',
			'name' => 'required|string|min:1|max:20',
			'phone' => 'required|phone:CN,mobile|unique:users',
			'password' => 'required|string|min:6|max:20', 
			'sms_key' => 'required|string',
			'sms_code' => ['required', 'string', 'min:4', 'max:4', $this->smsCode()],
			'agreement' => ['required', 'boolean', $this->agreement()],
			'is_allowed' => 'required|boolean',
		];
	}

	public function attributes(): array
	{
		return [
			'invite_code' => '邀请码',
			'name' => '微信昵称',
			'sms_key' => '短信验证码密钥',
			'sms_code' => '短信验证码',
			'agreement' => '用户协议'
		];
	}

	public function smsCode(): Closure
	{
		return function ($attribute, $value, $fail) {
			$sms = app(Sms::class);
			$verification = $sms->isSmsDataRight(request('sms_key'), request('phone'), $value);
			if (! $verification) {
				return $fail('短信验证码无效');
			}
			return true;
		};
	}

	public function agreement(): Closure
	{
		return function ($attribute, $value, $fail) {
			if (! $value) {
				return $fail('请先阅读用户协议');
			}
			return true;
		};
	}
}
